import { ElMessage } from 'element-plus'
import { ColumnsTypes, FormItemParams } from '../types'

export const useFormItem = (
  detailApiRequest: (params: any) => Promise<any>,
  addApiRequest: (params: any) => Promise<any>,
  updateRequest: (params: any) => Promise<any>,
  columns: ColumnsTypes[],
  key = 'id'
) => {
  const state = reactive<FormItemParams>({
    isAdd: false,
    readonly: false,
    id: 0,
    formColumns: [],
    model: {},
    rules: {},
    visibleDrawer: false
  })

  /**
   * 初始化表单项
   */
  const initForm = () => {
    state.formColumns = []
    state.model = {}
    state.rules = {}

    state.formColumns = columns.filter((item) => !item.hideInForm)

    state.formColumns.map((item) => {
      state.model[item.prop!] = item.value
      state.rules[item.prop!] = item.rules
    })
  }

  /** 获取表单项详情数据 */
  const fetchFormItemDetail = async () => {
    try {
      state.model = {}
      const res = await detailApiRequest(state.id)

      res.code === 200 &&
        Object.assign(state.model, res.data, {
          orderNum: +res?.data?.orderNum || 0,
          status: +res?.data?.status || 0
        })
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * 重置表单项
   */
  const resetForm = () => {
    state.model = {}
    state.isAdd = false
    state.readonly = false
    state.id = 0
    state.formColumns.map((item) => {
      state.model[item.prop!] = item.value
    })
  }

  /**
   * 打开表单
   * @param params id => 详情id isNew => 是否是新增(false => 修改) isRead => 是否是只读
   */
  const open = async (params: {
    id?: number
    isNew?: boolean
    isRead?: boolean
  }) => {
    const { id, isNew, isRead } = params
    state.isAdd = isNew ? isNew : false
    state.readonly = isRead ? isRead : false
    state.id = id ? id : 0
    !state.isAdd && state.id && (await fetchFormItemDetail())

    state.visibleDrawer = true
  }

  /**
   * 关闭表单项
   */
  const close = () => {
    state.visibleDrawer = false
    resetForm()
  }

  /**
   * 提价表单
   */
  const submit = async () => {
    try {
      const params = { ...state.model }
      let res
      switch (state.isAdd) {
        case true:
          params[key] = null
          res = await addApiRequest(params)
          break
        case false:
          res = await updateRequest(params)
          break
      }
      res.code === 200 && ElMessage.success('提交成功！')
      close()
    } catch (err) {
      console.log(err)
    }
  }

  return {
    ...toRefs(state),
    initForm,
    fetchFormItemDetail,
    resetForm,
    open,
    close,
    submit
  }
}
